/*
 * Copyright (c) 2017 Solidwang. All Rights Reserved
 */
package com.solid4j.auth.service.impl;

import com.solid4j.auth.dao.BaseDao;
import com.solid4j.auth.model.Privilege;
import com.solid4j.auth.model.Role;
import com.solid4j.auth.page.Page;
import com.solid4j.auth.service.PageService;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: solidwang
 * @date: 17/4/28
 */
@Component("pageService")
public class PageServiceImpl implements PageService {

    @Resource
    SessionFactory sessionFactory;

    @Resource
    private BaseDao<Privilege> baseDao;

    @Override
    public <T> Integer queryObjCount(Page<T> page) {
        StringBuffer queryHQL = new StringBuffer("SELECT COUNT(*) FROM " + page.getObjName());
        // 如果查询条件不为空
        if (page.getCondition() != null && !page.getCondition().trim().equals("")) {
            queryHQL.append(" WHERE " + page.getCondition());
        }
        // 如果排序不为空
        if (page.getOrderBy() != null && !page.getOrderBy().trim().equals("")) {
            queryHQL.append(" order by " + page.getOrderBy());
        }
        return Integer.parseInt(sessionFactory.getCurrentSession().createQuery(queryHQL.toString()).uniqueResult()
                .toString());
    }

    @Override
    public <T> Page<T> queryObjList(Page<T> page) {
        StringBuffer queryHQL = new StringBuffer();
        if (page.getQueryFields() != null && !page.getQueryFields().trim().equals("")) {
            queryHQL.append("SELECT " + page.getQueryFields() + " FROM " + page.getObjName());
        } else {
            queryHQL.append("FROM " + page.getObjName());
        }
        if (page.getCondition() != null && !page.getCondition().trim().equals("")) {
            queryHQL.append(" WHERE " + page.getCondition());
        }
        if (page.getOrderBy() != null) {
            queryHQL.append(" order by " + page.getOrderBy());
        }
        Query query = sessionFactory.getCurrentSession().createQuery(queryHQL.toString());
        query.setFirstResult(page.getStartIndex());
        query.setMaxResults(page.getPageSize());
        page.setTotalCount(this.queryObjCount(page));
        page.setObjList(query.list());
        return page;
    }
}
